package com.health.es.generate;

import com.health.es.entity.data.EsOpcPrescription;
import com.health.es.entity.data.EsOpcPrescriptionDetail;
import com.health.es.temp.EsHelper;
import lombok.SneakyThrows;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @author nqlz
 */
@Component
public class OpcPrescriptionDetailGenerate extends GenerateExecute<EsOpcPrescriptionDetail> {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    @PostConstruct
    protected void initClasses() {
        addClasses(EsOpcPrescriptionDetail.class);
    }

    @Override
    @SneakyThrows
    public void run(Collection<?> objects, Class<EsOpcPrescriptionDetail> tClass) {
        List<EsOpcPrescriptionDetail> tList = objects.parallelStream()
                .map(t -> executeEntity(t, tClass))
                .peek(this::tellMainOpc)
                .collect(Collectors.toList());
        EsHelper.operations.save(tList);
    }


    /**
     * 告诉主表opc
     * 主表信息先入库情况
     * 主先，查询 并修改
     * 子先，无需关注
     *
     * @param t t
     */
    private void tellMainOpc(EsOpcPrescriptionDetail t) {
        //获取关联的主键值
        MatchPhraseQueryBuilder builder = QueryBuilders.matchPhraseQuery("prescriptMainId", t.getPrescriptMainId());
        MatchPhraseQueryBuilder hospCode = QueryBuilders.matchPhraseQuery("hospCode", t.getHospCode());
        Optional<EsOpcPrescription> first = Optional.ofNullable(EsHelper.searchOne(EsOpcPrescription.class, builder,hospCode));
        first.ifPresent(i -> {
            //修改单独 关联值
            if (i.getDetailCount() < 1) {
                i.setDetailCount(i.getDetailCount() + 1);
                EsHelper.operations.save(i);
            }
        });
    }

}
